package com.xkk.config;

import com.xkk.mapper.RegisterMapper;
import com.xkk.mapper.RegisterMapper;
import com.xkk.pojo.Register;
import com.xkk.service.RegisterService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的，然后继承AuthorizingRealm加重写
public class UserRealm extends AuthorizingRealm {
    @Autowired
   RegisterService registerService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权");

        //SimpleAuthorizationInfo 给予用户一个权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //拿到当前登录的对象，pojo中间的那个自定义的Register
        Subject subject = SecurityUtils.getSubject();
        Register currentUser = (Register)subject.getPrincipal();//拿到对象
        return simpleAuthorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //获取数据库信息，最重要的一步
        Register register = registerService.queryByUserName(userToken.getUsername());

        if(register==null){
            return null; //抛出异常  UnknownAccountException
        }
        /*密码认证*/
        return new SimpleAuthenticationInfo(register,register.getPassword(),"");
    }

}
